<?php
require_once dirname(__FILE__).'/ImportBase.php';
require_once dirname(__FILE__).'/ImportFunction.php';
class ImportThread extends ImportBase{

	private static $instance;
	private $per_num=500; //每次导的条数
	private $img_url_prefix='http://forum.anjuke.com/attachments/';

    public static function &get_instance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

	private function get_thread_count($fid){
		$sql="select count('x') from cdb_threads where fid=? and displayorder>=0";
		$stmt=$this->dz_pdo->prepare($sql);
		$stmt->execute(array($fid));
		return $stmt->fetchColumn();
	}

	private function get_thread_list($fid,$offset,$per_num){
		$sql="select * from cdb_threads where fid=? and displayorder>=0 and special=0 order by tid asc limit $offset,$per_num";
		$stmt=$this->dz_pdo->prepare($sql);
		$stmt->execute(array($fid));
		return $stmt->fetchAll();
	}

	private function get_thread_info($tid){
		$sql="select * from cdb_threads where tid=?";
		$stmt=$this->dz_pdo->prepare($sql);
		$stmt->execute(array($tid));
		return $stmt->fetch();
	}

	private function get_post_list($tid){
		$sql="select * from cdb_posts where tid=? order by pid asc";
		$stmt=$this->dz_pdo->prepare($sql);
		$stmt->execute(array($tid));
		return $stmt->fetchAll();
	}

	private function get_attachment_list($pid){
		$sql="select aid,filename,attachment,isimage,thumb from cdb_attachments where pid=? order by aid asc";
		$stmt=$this->dz_pdo->prepare($sql);
		$stmt->execute(array($pid));
		return $stmt->fetchAll();
	}

	private function convert_attach_to_content($pid,$content){
		$attachment_list=$this->get_attachment_list($pid);
		if($attachment_list){
			foreach($attachment_list as $v){
				$attachment=$this->img_url_prefix.$v['attachment'];
				if($v['thumb']==1){
					$tpl='[img]'.$attachment.'.thumb.jpg[/img]';
					$tpl='[url='.$attachment.']'.$tpl.'[/url]';
				}elseif($v['isimage']==1){
					$tpl='[img]'.$attachment.'[/img]';
				}else{
					$tpl='[url='.$attachment.']'.$v['filename'].'[/url]';
				}
				$search='[attach]'.$v['aid'].'[/attach]';
				if(strstr($content, $search)){
					$content=str_replace($search,$tpl,$content);
				}else{
					$content=$content."\r\n".$tpl;
				}
			}
		}
		return $content;
	}

	private function add_one_thread($params){
		$sql="insert into threads set forum_id=?,title=?,author_id=?,top=?,highlight_style=?,highlight_color=?,digest=?,creation=?,updated=?";
		$stmt=$this->bbs_pdo->prepare($sql);
		$stmt->execute(array($params['forum_id'],$params['title'],$params['author_id'],$params['top'],$params['highlight_style'],$params['highlight_color'],$params['digest'],$params['creation'],$params['updated']));
		return $this->bbs_pdo->lastInsertId();
	}

	private function add_one_thread_ext($params){
		$sql="insert into threads_ext set id=?,posts=?,lastpost=?,views=?";
		$stmt=$this->bbs_pdo->prepare($sql);
		$stmt->execute(array($params['id'],$params['posts'],$params['lastpost'],$params['views']));
		return $stmt->rowCount();
	}

	//更新主题回复的ID进入主题表
	private function update_one_thread_post_id($post_id,$thread_id){
		if(!$post_id||!$thread_id)return false;
		$sql="update threads set post_id=? where id=".$thread_id;
		$stmt=$this->bbs_pdo->prepare($sql);
		$stmt->execute(array($post_id));
		return $stmt->rowCount();
	}

	private function add_one_post($params){
		$set='';
		if($params['updated']){
			$set=',updated=\''.$params['updated'].'\'';
		}
		$sql="insert into posts set parent_id=?,author_id=?,content=?,creation=?,ip=?".$set;
		$stmt=$this->bbs_pdo->prepare($sql);
		$stmt->execute(array($params['parent_id'],$params['author_id'],$params['content'],$params['creation'],$params['ip']));
		return $this->bbs_pdo->lastInsertId();
	}

	private function add_one_reply($post_id,$thread_id,$author_id){
		$sql="insert into replies set id=?,thread_id=?,author_id=?,status=?";
		$stmt=$this->bbs_pdo->prepare($sql);
		$stmt->execute(array($post_id,$thread_id,$author_id,'1'));
		return $stmt->rowCount();
	}

	private function add_map_thread($params){
		$sql="insert into map_thread set old_thread_id=?,new_thread_id=?";
		$stmt=$this->bbs_pdo->prepare($sql);
		$stmt->execute(array($params['old_thread_id'],$params['new_thread_id']));
		return $this->bbs_pdo->lastInsertId();
	}

	public function import_one_thread($tid,$to_forum_id){
		$thread_info=$this->get_thread_info($tid);
		if(!$thread_info){
			$this->print_msg('tid:'.$tid.' 主题内容不存在，跳过');
			return false;
		}
		$post_list=$this->get_post_list($tid);
		if(!$post_list){
			$this->print_msg('tid:'.$tid.' 回复内容不存在，跳过');
			return false;
		}

		$thread_attr['forum_id']=$to_forum_id;
		$thread_attr['title']=ImportFunction::un_dhtmlspecialchars($thread_info['subject']);
		$thread_attr['author_id']=$this->get_user_id($thread_info['author']);
		$thread_attr['top']=($thread_info['displayorder']>0)?1:0;
		list($highlight_style,$highlight_color)=ImportFunction::convert_highlight($thread_info['highlight']);
		$thread_attr['highlight_style']=$highlight_style;
		$thread_attr['highlight_color']=$highlight_color;
		$thread_attr['digest']=$thread_info['digest'];
		$thread_attr['creation']=date("Y-m-d H:i:s",$thread_info['dateline']);
		$thread_attr['updated']=date("Y-m-d H:i:s",$thread_info['lastpost']);
		$thread_id=$this->add_one_thread($thread_attr);
		if(!$thread_id){
			$this->print_msg('tid:'.$tid.' 插入主题发生数据库错误');
			return false;
		}

		$map_thread_attr['old_thread_id']=$tid;
		$map_thread_attr['new_thread_id']=$thread_id;
		$map_res=$this->add_map_thread($map_thread_attr);
		if(!$map_res){
			$this->print_msg('tid:'.$tid.' 插入map_thread发生数据库错误');
			return false;
		}

		$post_count=count($post_list);

		foreach($post_list as $pk=>$pv){
			$author_id=$this->get_user_id($pv['author']);
			$post_attr['parent_id']=0;
			$post_attr['author_id']=$author_id;
			$content=$pv['message'];
			//引用
			$content=preg_replace('/\[url=http:\/\/forum\.anjuke\.com\/redirect.php\?goto=findpost&.*\[img\]http:\/\/forum\.anjuke\.com\/images\/common\/back.gif\[\/img\]\[\/url\]/i','',$content);
			//最后编辑
			preg_match('/\[\[i\].*本帖最后由.*于\s*(.*?)\s*编辑.*\[\/i\]\]$/',$content,$match);
			if($match[0]){
				$content=preg_replace('/\[\[i\].*本帖最后由.*于\s*(.*?)\s*编辑.*\[\/i\]\]$/','',$content);
			}
			if($match[1]){
				$post_attr['updated']=$match[1];
			}else{
				$post_attr['updated']='';
			}
			if($pv['attachment']==1){
				$content=$this->convert_attach_to_content($pv['pid'],$content);
			}
			$post_attr['content']=$content;
			$post_attr['creation']=date("Y-m-d H:i:s",$pv['dateline']);
			$post_attr['ip']=$pv['useip'];
			$post_id=$this->add_one_post($post_attr);
			if($post_id){
				//主题
				if($pk=='0'){
					$this->update_one_thread_post_id($post_id,$thread_id);
				}
				if(($post_count-$pk)==1){
					$thread_ext_attr['id']=$thread_id;
					$thread_ext_attr['posts']=$post_count;
					$thread_ext_attr['views']=$thread_info['views'];
					$thread_ext_attr['lastpost']=$post_id."\t".$post_attr['creation']."\t".$pv['author'];
					$this->add_one_thread_ext($thread_ext_attr);
				}
				$this->add_one_reply($post_id,$thread_id,$author_id);
			}else{
				$this->print_msg('tid:'.$tid.' pid:'.$pv['pid'].' 插入posts发生数据库错误');
			}
		}
	}

	public function run($fids){

		foreach($fids as $old_forum_id=>$new_forum_id){
			$this->print_msg("开始导入版块老ID：".$old_forum_id." 到 新ID：".$new_forum_id);

			$threads_count=$this->get_thread_count($old_forum_id);
			$this->print_msg("共有".$threads_count."条记录需要导入");

			for($i=0;$i<$threads_count;$i=$i+$this->per_num){
				$this->print_msg("导入第".$i."条开始的".$this->per_num."条记录");
				$thread_list=$this->get_thread_list($old_forum_id,$i,$this->per_num);
				if(!$thread_list){
					continue;
				}
				foreach($thread_list as $threadk=>$threadv){
					$this->import_one_thread($threadv['tid'],$new_forum_id);
				}
			}
			$this->print_msg("结束导入版块老ID：".$old_forum_id." 到 新ID".$new_forum_id);
		}

	}

}

$fids=array('28'=>'7');
ImportThread::get_instance()->run($fids);
//ImportThread::get_instance()->import_one_thread(12199,1);